import { takeEvery, put} from 'redux-saga/effects'
import axios from 'axios'
import {load_todo_success, load_todo,
  add_todo,add_todo_success,
  remove_todo,remove_todo_success,
  modify_todo, modify_todo_success,
  clear_todo_completed,clear_todo_completed_success,
  edit_todo, edit_todo_success,
rename_todo,rename_todo_success} from '../actions/todo.actions'

function* load_todo_data(){
  let todoData = yield axios.get('http://localhost:3005/api/todos').then(res => res.data)
  console.log(todoData)
  yield put(load_todo_success(todoData))
}

function* add_todo_data(action){
  console.log(action)
  let todoData = yield axios.post('http://localhost:3005/api/todos',{taskName: action.payload}).then(res => res.data)
  console.log(todoData)
  yield put(add_todo_success(todoData.task))
}

function* remove_todo_data(action){
  console.log(action)
  let todoData = yield axios.delete('http://localhost:3005/api/todos',{
    params:{
      id: action.payload
    }
  }).then(res => res.data)
  console.log(todoData)
  yield put(remove_todo_success(todoData.tasks.id))
}
function* modify_todo_data(action){
  console.log(action)
  let todoData = yield axios.put('http://localhost:3005/api/todos/isCompleted',action.payload).then(res => res.data)
  console.log(todoData)
  yield put(modify_todo_success(todoData.task))
}

function* clear_todo_completed_data(){
  let todoData = yield axios.delete('http://localhost:3005/api/todos/clearCompleted').then(res => res.data)
  console.log(todoData)
  yield put(clear_todo_completed_success(todoData.task))
}

function* edit_todo_data(action){
  let todoData = yield axios.put('http://localhost:3005/api/todos/isEditing',action.payload).then(res => res.data)
  console.log(todoData)
  yield put(edit_todo_success(todoData.task))
}

function* rename_todo_data(action){
  let todoData = yield axios.put('http://localhost:3005/api/todos',action.payload).then(res => res.data)
  console.log(todoData)
  yield put(rename_todo_success(todoData.task))
}
// 完成异步操作
//  重新发送新的指令
export default function* todoSaga(){
  yield takeEvery(load_todo, load_todo_data)
  yield takeEvery(add_todo, add_todo_data)
  yield takeEvery(remove_todo, remove_todo_data)
  yield takeEvery(modify_todo, modify_todo_data)
  yield takeEvery(clear_todo_completed, clear_todo_completed_data)
  yield takeEvery(edit_todo, edit_todo_data)
  yield takeEvery(rename_todo, rename_todo_data)



}